//
//  MCIconManag.m
//  QuKeClient
//
//  Created by delicious on 2017/12/26.
//  Copyright © 2017年 delicious. All rights reserved.
//

#import "MCIconManage.h"
#import "LLActionSheetView.h"
#import "UIActionSheet+NTESBlock.h"
@interface UIViewController (Message)
+ (void)showAlertWithTitle: (NSString *)title message: (NSString *)message actionTitles: (NSArray<NSString *> *)actions cancelTitle: (NSString *)cancelTitle style: (UIAlertControllerStyle)style completion: (void(^)(NSInteger index))completion;
@end
@implementation UIViewController (Message)

+ (void)showAlertWithTitle: (NSString *)title message: (NSString *)message actionTitles: (NSArray<NSString *> *)actions cancelTitle: (NSString *)cancelTitle style: (UIAlertControllerStyle)style completion: (void(^)(NSInteger index))completion {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:style];
    for (NSInteger index = 0; index < actions.count; index++) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:actions[index] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            !completion ?  : completion(index);
        }];
        [alert addAction:action];
    }
    if (cancelTitle.length) {
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:cancelTitle style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:cancel];
    }
    UIViewController *vc = [[UIApplication sharedApplication] keyWindow].rootViewController;
    [vc presentViewController:alert animated:YES completion:nil];
}


@end



@interface MCIconManage()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (nonatomic, copy) ReturnImage returnImage;
@property (nonatomic, copy) ReturnError returnError;
@end

@implementation MCIconManage

-(void)dealloc
{
    NSLog(@"图片选择管理释放了");
}

+(instancetype)onImageForVC:(UIViewController *)vc canEditImage:(BOOL)edit ReturnImage:(ReturnImage)returnImage
{
     return [MCIconManage onImageForVC:vc canEditImage:edit ReturnImage:returnImage ReturnError:nil];
}
+(instancetype)onImageForVC:(UIViewController *)vc ReturnImage:(ReturnImage)returnImage
{
     return [MCIconManage onImageForVC:vc canEditImage:NO ReturnImage:returnImage ReturnError:nil];
}

+(instancetype)onImageForVC:(UIViewController *)vc ReturnImage:(ReturnImage)returnImage ReturnError:(ReturnError)error
{
    return [MCIconManage onImageForVC:vc canEditImage:NO ReturnImage:returnImage ReturnError:error];
}


+(instancetype)onImageForVC:(UIViewController *)vc canEditImage:(BOOL)edit ReturnImage:(ReturnImage)returnImage ReturnError:(ReturnError)error Titles:(NSArray *)titles
{
     return [MCIconManage onImageForVC:vc canEditImage:NO isSheetView:YES ReturnImage:returnImage ReturnError:error Titles:titles];
}
+(instancetype)onImageForVC:(UIViewController *)vc canEditImage:(BOOL)edit isSheetView:(BOOL)isSheetView ReturnImage:(ReturnImage)returnImage ReturnError:(ReturnError)error Titles:(NSArray *)titles;

{
    MCIconManage *iconManage = [MCIconManage new];
    iconManage.returnImage = returnImage;
    if (isSheetView) {
        //WSELF(weakSelf);
        LLActionSheetView *sheetView = [[LLActionSheetView alloc]initWithTitleArray:titles andShowCancel:YES];
        sheetView.ClickIndex = ^(NSInteger index) {
            
            if (index!=0) {
                if (index==1) {
                    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
                    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
                        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                        picker.delegate = iconManage;//weakSelf;
                        //设置拍照后的图片可被编辑
                        picker.allowsEditing = edit;
                        picker.sourceType = sourceType;
                        
                        [vc presentViewController:picker animated:YES completion:nil];
                        
                    }else{
                        [UIAlertController showAlertWithTitle:@"该设备不支持拍照" message:nil actionTitles:@[@"确定"] cancelTitle:nil style:UIAlertControllerStyleAlert completion:nil];
                    }
                    
                }
                else if (index==2)
                {
                    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                    picker.delegate = iconManage;//weakSelf;
                    //设置拍照后的图片可被编辑
                    picker.allowsEditing = edit;
                    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    [vc presentViewController:picker animated:YES completion:nil];
                    
                }
                
            }else
            {
                [iconManage removeFromSuperview];
            }
            
        };
        [sheetView show];
    }else
    {
        UIActionSheet *sheetView = [UIActionSheet onCreatWithTitle:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:titles];
        [sheetView showInView:vc.view completionHandler:^(NSInteger index) {
             if (index!=0) {
                if (index==1) {
                    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
                    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
                        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                        picker.delegate = iconManage;//weakSelf;
                        //设置拍照后的图片可被编辑
                        picker.allowsEditing = edit;
                        picker.sourceType = sourceType;
                        
                        [vc presentViewController:picker animated:YES completion:nil];
                        
                    }else{
                        [UIAlertController showAlertWithTitle:@"该设备不支持拍照" message:nil actionTitles:@[@"确定"] cancelTitle:nil style:UIAlertControllerStyleAlert completion:nil];
                    }
                    
                }
                else if (index==2)
                {
                    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
                    picker.delegate = iconManage;//weakSelf;
                    //设置拍照后的图片可被编辑
                    picker.allowsEditing = edit;
                    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    [vc presentViewController:picker animated:YES completion:nil];
                    
                }
            }else
            {
                 [iconManage removeFromSuperview];
            }
            
        }];
    }
    [vc.view addV:iconManage];
    
    return iconManage;
}

+(instancetype)onImageForVC:(UIViewController *)vc canEditImage:(BOOL)edit ReturnImage:(ReturnImage)returnImage ReturnError:(ReturnError)error
{
    return [MCIconManage onImageForVC:vc canEditImage:edit ReturnImage:returnImage ReturnError:error Titles:@[@"照相机",@"相册"]];
    
}

#pragma mark - UIImagePickerController Delegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(nullable NSDictionary<NSString *,id> *)info
{
    
    //        UIImage * newImage = [info objectForKey:UIImagePickerControllerEditedImage];
    //        //如果 picker 没有设置可编辑，那么image 为 nil
    //        if (newImage == nil) {
    //            newImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    //        }
           __weak typeof(self)weakSelf=self;
    dispatch_async(dispatch_get_main_queue(), ^{
        weakSelf.returnImage(weakSelf,image);
    });
    [picker dismissViewControllerAnimated:YES completion:^{
        [weakSelf removeFromSuperview];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
           __weak typeof(self)weakSelf=self;
    [picker dismissViewControllerAnimated:YES completion:^{
        if (weakSelf.returnError) {
            weakSelf.returnError(@"取消");
        }
        [weakSelf removeFromSuperview];
    }];
    
    
}


#pragma mark 图片处理方法
//图片旋转处理
- (UIImage *)fixOrientation:(UIImage *)aImage {
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}


@end



